package com.wuyou.mid;

import java.util.*;

/**
 * 找到 K 个最接近的元素
 */
public class FindClosestElements {

    public static void main(String[] args) {
//        int[] arr = {0,0,1,2,3,3,4,7,7,8};
//        int k = 3;
//        int x = 5;
//        int[] arr = {1, 1, 2, 2, 2, 2, 2, 3, 3};
//        int k = 3;
//        int x = 3;
        int[] arr = {1,1,2,3,3,3,4,6,8,8};
        int k = 6;
        int x = 1;

        System.out.println(solution_2(arr, k, x));
    }

    public static List<Integer> solution_2(int[] arr, int k, int x) {
        int maxSub = 0;
        List<Integer> res = new ArrayList<Integer>();
        List<Integer> subList = new ArrayList<Integer>();
        for (int i : arr) {
            subList.add(Math.abs(i - x));
        }
        Collections.sort(subList);
        System.out.println(subList);
        while (res.size() != k) {
            for (int i = 0; i < arr.length; i++) {
                if (Math.abs(arr[i] - x) == subList.get(res.size())) {
                    res.add(arr[i]);
                    arr[i] = 2147483647;
                    break;
                }
            }
        }
        Collections.sort(res);
        return res;
    }

    public static List<Integer> solution_1(int[] arr, int k, int x) {

        List<Integer> ans = new ArrayList<Integer>();
        for (Integer num : arr) {
            ans.add(num);
        }
        Collections.sort(ans, (a, b) -> {
            System.out.println(a + " " + b);
            if (Math.abs(a - x) != Math.abs(b - x)) {
                int num = Math.abs(a - x) - Math.abs(b - x);
                System.out.println("num-" + num);
                return num;
            } else {
                return a - b;
            }
        });
        List<Integer> res = ans.subList(0, k);
        Collections.sort(res);
        return res;
    }
}
